package cn.xz.hfsk.util;


import static android.content.ContentValues.TAG;

import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.regex.Pattern;

import cn.xz.hfsk.bean.Flash;
import cn.xz.hfsk.bean.FlashList;
import cn.xz.hfsk.net.OkHttpUtil;
import cn.xz.hfsk.net.OkhttpResponseHandle;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 本地内容播放器接口
 * */
public class LocalHttp {

    //本地端口号-默认 8020，后根据需求修改
    private static final int mPort = 8020;

    /*
     * @param ip
     * @param port
     * @param type
     * 1:播放
     * 2:暂停
     * 3:重播
     * 5:上一个
     * 6:下一个
     * 7：上一页
     * 8：下一页
     * 9：列表上一个
     * 10：列表下一个
     * 11：隐藏客户端
     * 12：显示客户端
     */
    public static void moviePlay(String ip, int port, int type) {
        String url = "http://" + ip + ":" + port + "/?act=movie&object=&states=" + type + "&r=" + (int) (Math.random() * 10000);
        OkHttpUtil.post(url);
    }

    public static void moviePlay(String ip,int type) {
        String url = "http://" + ip + ":" + mPort + "/?act=movie&object=&states=" + type + "&r=" + (int) (Math.random() * 10000);
        OkHttpUtil.post(url);
    }

    /*如果是程序和本地播放混合在一起的,点击哪个按钮要灵活转换界面
     *默认点播本地资源事，本地播放器会自动显示出来
     * */

    //点播本地资源 - 自带端口号
    public static void playLocal(String ip, int port, int index){
        OkHttpUtil.post("http://" + ip + ":" + port + "/?act=movie" + "&object=" + index + "&states=13");
    }

    //点名本地资源 - 默认端口号
    public static void playLocal(String ip, int index){
        OkHttpUtil.post("http://" + ip + ":" + mPort + "/?act=movie" + "&object=" + index + "&states=13");
    }

    //获取本地资源列表
    //获取数据通用回调，因为请求异步，加回调判断
    public interface GetPlayDataListener{
        void getData(ArrayList<Flash> list); //有参方法
    }
    public static void getPlayData(Context context,String ip, GetPlayDataListener mListener){
        String url = "http://" + ip + ":" + mPort + "/?act=movie&object=&states=14";
        OkHttpUtil.get(context, url, FlashList.class, new OkhttpResponseHandle<FlashList>() {
            @Override
            public void onSuccess(final FlashList response) {
                if (response.getList() != null && response.getList().size() > 0) {
                    mListener.getData((ArrayList<Flash>) response.getList());
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                Log.e(TAG, "本地内容播放器接口:失败->" + "获取本地资源列表");
                mListener.getData(new ArrayList<Flash>());
            }
        });
    }

    //获取本机音量
    public interface GetVoiceSizeListener{
        void getData(int progress); //有参方法
    }
    public static void getVoiceSize(String ip,GetVoiceSizeListener  mListener){
        String voiceUrl = "http://" + ip + ":8088/?act=getvolume&r=" + (int) (Math.random() * 10000);
        OkHttpUtil.get(voiceUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "本地内容播放器接口:失败->" + "获取本机音量");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String re = response.body().string().trim();
                    if (re == null) {
                        return;
                    }
                    BigDecimal bigDecimal = new BigDecimal(re);
                    int progress = bigDecimal.intValue();
                    mListener.getData(progress);
                }
            }
        });
    }

    //修改本机音量
    public static void changeVoice(String ip,int progress){
        OkHttpUtil.post("http://" + ip + ":8088/?act=setvolume&object=&states=" + progress + "&r=" + (int) (Math.random() * 10000));
    }


    //获取当前视频进度
    public interface GetMovieSizeListener{
        void getData(String maxTxt,String minTxt,int maxSeekBar,int seekProgress); //有参方法
    }
    public static void getMovieSize(String ip,GetMovieSizeListener mListener){
        String movieUrl = "http://" + ip + ":" + mPort + "/?act=movie&object=&states=17&r=" + (int) (Math.random() * 10000);
        OkHttpUtil.get(movieUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "本地内容播放器接口:失败->" + "获取视频进度");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseString = response.body().string();
                    //如果请求数据长度小于6直接不处理，服务端只要请求成功就会返回true，
                    // 这里截取前面字符串判断一下，要截取前几个，正常返回数据里也可能会有
                    if (responseString.length() > 6 && responseString.substring(0,5).contains("true")){
                        return;
                    }
                    String[] strs = responseString.split("\\|");
                    if (strs.length == 2) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e("str1", strs[0]);
                                Log.e("str1", strs[1]);
                                int a = 0;
                                int b = 0;
                                if (isNumeric(strs[0].substring(0, 1))) {
                                    if (isNumeric(strs[0])) {
                                        a = Integer.parseInt(strs[0]);
                                    } else {
                                        a = Double.valueOf(strs[0]).intValue();
                                    }
                                } else {
                                    if (isNumeric(strs[0])) {
                                        a = Integer.parseInt(strs[0]);
                                    } else {
                                        a = Double.valueOf(strs[0].substring(1, strs[0].length())).intValue();

                                    }

                                }
                                if (isNumeric(strs[1])) {
                                    b = Integer.parseInt(strs[1]);
                                } else {
                                    b = Double.valueOf(strs[1]).intValue();
                                }
                                int max = Math.max(a, b);
                                int min = Math.min(a, b);
                                mListener.getData(
                                        TimeUtils.getTime(Math.max(a, b)),
                                        TimeUtils.getTime(Math.min(a, b)),
                                        Math.max(a, b),
                                        Math.min(a, b)
                                        );
                            }
                        }).start();
                    }
                }
            }
        });
    }


    //修改当前视频进度
    public static void changeMovie(String ip,int progress){
        OkHttpUtil.post("http://" + ip + ":" + mPort + "/?act=movie&object=" + progress + "&states=4&r=" + (int) (Math.random() * 10000));
    }


    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }
}
